package com.yhb.utils;

import me.edzh.spring.bootstrap.processor.SignAndEncryptProcessor;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Service("signer")
public class SignConfig implements SignAndEncryptProcessor.SignConfig {
    private static final String SIGN_SECRET = "L6Q7qYKigry6zn23S6DQq5w8PoPBbo";

    private static final String PWD_HASH_SECRET = "dB5XBXKgdNAtpKdhcLYfaZSWfi2v/dQtoO2hbGpi7XA=";
    private static final Mac mac;

    private static final Mac pwdMac;

    static {
        Mac m;
        SecretKeySpec spec;
        try {
            m = Mac.getInstance("HmacSHA256");
            spec = new SecretKeySpec(SIGN_SECRET.getBytes(), "HmacSHA256");
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }

        mac = m;
        try {
            mac.init(spec);
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }

    }

    static {
        Mac m;
        SecretKeySpec spec;
        try {
            m = Mac.getInstance("HmacSHA256");
            spec = new SecretKeySpec(Base64.getDecoder().decode(PWD_HASH_SECRET), "HmacSHA256");
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }

        pwdMac = m;
        try {
            pwdMac.init(spec);
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }
    @Override
    public long timeStampInvalidThreshold() {
        return 300000;
    }

    @Override
    public String sign(String signStr) {
        return Hex.encodeHexString(mac.doFinal(signStr.getBytes())).toUpperCase();
    }

    public static String getHash(String content, String salt) {
        return Hex.encodeHexString(pwdMac.doFinal((content + salt).getBytes())).toUpperCase();
    }

    public static void main(String[] args) {
        System.out.println(getHash("12345678", "1ab05205-f285-11e9-b54a-00163e0c8cb0"));
    }
}
